package linkedlist;

import java.util.HashMap;
import java.util.Map;

public class LRUCache {

    private class CacheNode {

        CacheNode prev;

        CacheNode next;

        int key;

        int value;

        public CacheNode(int key, int value) {
            this.key = key;
            this.value = value;
            this.prev = null;
            this.next = null;
        }

    }

    private int capacity;

    private Map<Integer, CacheNode> nodeMap = new HashMap<>();

    private CacheNode head = new CacheNode(-1, -1);

    private CacheNode tail = new CacheNode(-1, -1);

    LRUCache(int capacity) {
        this.capacity = capacity;
        tail.prev = head;
        head.next = tail;
    }

    public int get(int key) {
        if (!nodeMap.containsKey(key)) {
            return -1;
        }
        CacheNode current = nodeMap.get(key);
        current.prev.next = current.next;
        current.next.prev = current.prev;
        moveToTail(current);
        return current.value;
    }

    public int put(int key, int value) {
        // 当key已存在
        if (nodeMap.containsKey(key)) {
            CacheNode cacheNode = nodeMap.get(key);
            cacheNode.value = value;
            return value;
        }
        // 当容量已满，删除头结点
        if (nodeMap.size() == capacity) {
            nodeMap.remove(key);
            head.next = head.next.next;
            head.next.prev = head;
        }
        // 插入新节点
        CacheNode insertNode = new CacheNode(key, value);
        nodeMap.put(key, insertNode);
        moveToTail(insertNode);
        return value;
    }

    private void moveToTail(CacheNode currentNode) {
        currentNode.prev = tail.prev;
        tail.prev = currentNode;
        currentNode.prev.next = currentNode;
        currentNode.next = tail;
    }


}
